<template>
  <BoTable
    :columns="columns"
    :request="getModelList"
    ref="tableRef"
    :row-selection="rowSelection"
    row-key="modelId"
    show-index
  >
    <template #toolbars>
      <Space :size="8">
        <Button type="primary" @click="onAdd"> 新增 </Button>
        <Button
          type="primary"
          :disabled="!selectKeys.length"
          @click="onDelete(null)"
        >
          删除
        </Button>
      </Space>
    </template>
  </BoTable>
  <FormModal :columns="items"> </FormModal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import { deviceEnum } from '@/constants';
import { useFormModal } from '@boeyo/hooks';
import { useDicts } from '@boeyo/portal';
import { listToEnum, listToOption } from '@boeyo/shared';
import { BoFormProps, BoTable, BoTableProps } from '@boeyo/ui';
import { Button, Modal, Space, Switch, message } from 'ant-design-vue';
import {
  addModel,
  deleteModel,
  getDeviceManufacturerSelect,
  getModelList,
  updateModel,
} from './api';

const tableRef = ref();
const selectKeys = ref<any[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    onChange(values, all) {
      selectKeys.value = values;
    },
  };
});

const dictArr = ['use_status', 'device_type'];
const { useStatusEnum, useStatusOptions, deviceTypeEnum, deviceTypeOptions } =
  useDicts(dictArr);

// 获取表单下拉框数据
const mnufacturerOptions = ref<any[]>([]);
const manufacturerEnum = ref<Record<string, any>>({});

const init = () => {
  getDeviceManufacturerSelect(deviceEnum.ALL).then(({ data }) => {
    mnufacturerOptions.value = listToOption(data, 'name', 'facId');
    manufacturerEnum.value = listToEnum(data, 'name', 'facId');
  });
};
init();

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '设备型号',
    dataIndex: 'model',
  },
  {
    title: '设备类型',
    dataIndex: 'type',
    valueType: 'select',
    valueEnum: deviceTypeEnum.value,
  },
  {
    title: '设备厂商',
    dataIndex: 'manufacturer',
    valueType: 'input',
    hideInSearch: true,
    ellipsis: true,
  },
  {
    title: '设备厂商',
    dataIndex: 'facId',
    valueType: 'select',
    valueEnum: manufacturerEnum.value,
    hideInTable: true,
  },
  {
    title: '型号版本',
    dataIndex: 'version',
    customRender: ({ text }) => {
      return <span style={{ color: '#3399ff' }}>{text}</span>;
    },
    hideInSearch: true,
  },
  {
    title: '启用状态',
    dataIndex: 'status',
    valueType: 'select',
    hideInTable: true,
    valueEnum: useStatusEnum.value,
  },
  {
    title: '是否启用', //（0正常 1停用）
    dataIndex: 'status',
    hideInSearch: true,
    customRender: ({ record }) => {
      return (
        <Switch
          checkedValue={'0'}
          unCheckedChildren={'未启用'}
          checkedChildren={'启用'}
          unCheckedValue={'1'}
          v-model:checked={record.status}
          onChange={() => onChange(record)}
        ></Switch>
      );
    },
  },
  {
    title: '灵敏度/格值(gal/mV)',
    dataIndex: 'sensitivity',
    hideInSearch: true,
  },
  {
    title: '转换因子(count/gal)',
    dataIndex: 'latticeValue',
    hideInSearch: true,
  },
  {
    title: '备注',
    dataIndex: 'modelDesc',
    hideInSearch: true,
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    valueType: 'datePicker',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions: [
      {
        text: '编辑',
        onClick(record) {
          onEdit(record);
        },
      },
      {
        text: '删除',
        onClick(record) {
          onDelete(record);
        },
      },
    ],
  },
]);

const items = computed<BoFormProps['columns']>(() => [
  {
    title: '设备型号',
    dataIndex: 'model',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入设备型号',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入设备型号',
    },
  },
  {
    title: '设备类型',
    dataIndex: 'type',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入设备类型',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入设备类型',
      options: deviceTypeOptions.value,
    },
  },
  {
    title: '型号版本',
    dataIndex: 'version',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入型号版本',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入型号版本',
    },
  },
  {
    title: '设备厂商',
    dataIndex: 'facId',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入设备厂商',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入设备厂商',
      options: mnufacturerOptions.value,
    },
  },
  {
    title: '灵敏度/格值',
    dataIndex: 'sensitivity',
    valueType: 'inputNumber',
    hidden: (state) => state.type !== '1',
    formItemProps: {
      tooltip: '灵敏度/格值为数值',
      rules: [
        {
          required: true,
          message: '请输入格值',
          trigger: 'blur',
        },
      ],
    },

    fieldProps: {
      placeholder: '请输入格值，为数字类型，允许小数',
      addonAfter: 'gal/mV',
    },
  },
  {
    title: '转换因子',
    dataIndex: 'latticeValue',
    valueType: 'inputNumber',
    hidden: (state) => state.type !== '1',
    formItemProps: {
      tooltip: '转换因子为正整数',
      rules: [
        {
          required: true,
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入转换因子，为正整数',
      precision: 0,
      addonAfter: 'count/gal',
    },
  },
  {
    title: '描述',
    dataIndex: 'modelDesc',
    valueType: 'textarea',
    formItemProps: {
      rules: [
        {
          required: false,
          message: '请输入描述',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入描述',
      rows: 4,
    },
  },
  {
    title: '是否启用',
    dataIndex: 'status',
    valueType: 'radio',
    fieldProps: {
      options: useStatusOptions.value,
    },
  },
]);

const { FormModal, open } = useFormModal({
  size: 'small',
  column: 1,
});

const onAdd = () => {
  open({
    title: '新增',
    request: async (params: any) => {
      await addModel(params);
      tableRef.value.refresh();
    },
    defaultValue: {
      status: '0',
    },
  });
};

const onEdit = async (record) => {
  open({
    title: '编辑',
    defaultValue: { ...record },
    request: async (params: any) => {
      await updateModel(params);
      tableRef.value.refresh();
    },
  });
};

const onDelete = async (record) => {
  const ids = record ? record.modelId : selectKeys.value.join(',');
  if (!ids) return message.info('请选择要删除的数据');
  Modal.confirm({
    title: '系统提示',
    content: `确定删除当前选中项数据吗?`,
    onOk: async () => {
      await deleteModel(ids);
      message.success('操作成功');
      tableRef.value.refresh();
    },
  });
};

const onChange = (record: any) => {
  const text = record.status == '1' ? '停用' : '启用';
  Modal.confirm({
    title: '系统提示',
    content: `确定${text}当前项吗?`,
    onOk: async () => {
      await updateModel(record);
      message.success('操作成功');
      tableRef.value.refresh();
    },
  });
  tableRef.value.refresh();
};
</script>

<style lang="scss" scoped>
.custom_title {
  padding-left: 10px;
  position: relative;
  &::before {
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    content: '';
    width: 3px;
    height: 10px;
    background-color: #40deff;
  }
}
</style>
<route lang="json">
{
  "name": "device-model",
  "meta": { "title": "设备型号管理" }
}
</route>
